package com.itqf.realm;

import com.itqf.bean.DtsAdmin;
import com.itqf.constants.ShiroConstants;
import com.itqf.service.DtsAdminService;
import com.itqf.service.DtsPermissionService;
import com.itqf.service.DtsRoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * projectName: gp_manage
 *
 * @author: 赵伟风
 * time: 2021/8/17 9:47
 * description:自定义数据库查询Realm
 *             密码是密文： 加密方式 md5 加密次数  md6   加密的盐  固定的盐 常量类/常量
 */
public class JdbcRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(JdbcRealm.class);

    @Autowired
    private DtsAdminService dtsAdminService;

    @Autowired
    private DtsRoleService dtsRoleService;

    @Autowired
    private DtsPermissionService dtsPermissionService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //1.获取primary principal --> doGetAuthenticationInfo return第一个参数
        DtsAdmin dtsAdmin = (DtsAdmin) principalCollection.getPrimaryPrincipal();

        if (dtsAdmin == null) {
            LOGGER.trace("[授权流程]-->[授权终止]-->[principal为null]-->[dtsAdmin]:{}",dtsAdmin);
            return null;
        }


        if (dtsAdmin.getRoleIds() == null || dtsAdmin.getRoleIds().length == 0){

            // error/warn  [类型：方法] --> [异常/警告信息]{} ---> [原因分析]:{} ---> [解决方案]：{} ---> [核心参数]：{}
            LOGGER.warn("[JdbcRealm:doGetAuthorizationInfo]-->[用户没有分配角色]" +
                    "-->[未进行角色分配！]-->[进行赋权]-->[username:roleIds]:{}:null",dtsAdmin.getUsername());

            return null;
        }


        //2.查询权限集合
        List<String> permissions =  dtsPermissionService.findPermissionsByRoleIds(dtsAdmin.getRoleIds());

        //3.查询角色集合
        List<String> names = dtsRoleService.findRoleNameByRoleIds(dtsAdmin.getRoleIds());

        //4.封装AuthorizationInfo中
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        authorizationInfo.addRoles(names);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        //1.获取用户输入的账号 principal
        String username = (String) authenticationToken.getPrincipal();

        if (StringUtils.isEmpty(username)) {

            //trace流程  【流程】-- 【流程状态】--【节点介绍】 --【核心参数】
            // [流程名]-->[状态]-->[节点介绍]-->[核心参数]
            LOGGER.trace("[认证流程]-->[认证终止]-->[用户名为null]--->[username]:{}",username);

            return null;
        }

        //2.数据库验证账号 dtsAdmin
        //查询 find-内容-条件
        DtsAdmin dtsAdmin  =  dtsAdminService.findAdminByUserName(username);

        //3.返回实体验证   null return null

        if (dtsAdmin == null) {

            LOGGER.trace("[认证流程]-->[认证终止]-->[用户名不匹配]--->[username]:{}",username);

            return null;
        }

        //4.封装返回数据结果 AuthenticationInfo(dtsadmin,密码，盐，标识)

        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(dtsAdmin,dtsAdmin.getPassword(),
                        ByteSource.Util.bytes(ShiroConstants.ADMIN_SALT), ShiroConstants.REALM_NAME);

        return authenticationInfo;
    }
}
